<template>
  <el-breadcrumb spearator="/" leading-50px text-14px ml-8px>
    <el-breadcrumb-item v-for="(item, index) in levelList" :key="item.path">
      <span v-if="index === levelList.length - 1" cursor-text>
        {{ item.meta?.title }}
      </span>
      <a v-else @click.prevent="handleLink(item)">
        {{ item.meta?.title }}
      </a>
    </el-breadcrumb-item>
  </el-breadcrumb>
</template>

<script setup lang="ts">
import type { RouteLocationMatched } from "vue-router"
import { compile } from "path-to-regexp"
const router = useRouter()
type PartialRouteLocationMatched = Partial<RouteLocationMatched>
const route = useRoute()
const levelList = ref<PartialRouteLocationMatched[]>([])

const pathCompile = (path: string) => {
  const toPath = compile(path)
  const params = route.params
  return toPath(params)
}

const handleLink = (route: PartialRouteLocationMatched) => {
  const { redirect, path } = route
  // 如果是重定向路由 就走重定向路径
  if (redirect) {
    router.push(redirect as string)
    return
  }
  router.push(pathCompile(path!))
}

// 1.判断是不是Dashboard路由
const isDashboard = (route?: PartialRouteLocationMatched): boolean => {
  return route?.path === "/dashboard"
}

// 2.获取面包屑导航
const getBreadcrumb = () => {
  // 1).有title才显示面包屑导航
  let matched = route.matched.filter(
    (item) => item.meta?.title
  ) as PartialRouteLocationMatched[]
  // 2).第一个不是dashboard，在前面增加dashboard
  if (!isDashboard(matched[0])) {
    matched = [
      {
        path: "/dashboard",
        meta: {
          title: "dashboard"
        }
      },
      ...matched
    ]
  }
  // 过滤掉breadcrumb为false的情况
  levelList.value = matched.filter((item) => item.meta?.breadcrumb !== false)
}

watch(() => route.path, getBreadcrumb, { immediate: true })
</script>
